package org.example.demo_xiaowuz.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.demo_xiaowuz.model.Result;
import org.example.demo_xiaowuz.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginCheckInterceptor.class);
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        log.info("检验用户是否登录");
        HttpSession session=request.getSession();
        UserInfo userInfo=(UserInfo) session.getAttribute("session_user_key");
        if(userInfo==null) {
            log.warn("用户未登录");
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            Result result = Result.fail("用户未登录");
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            return false;
        }
        log.info("放行");
        return true;
    }
}
